package com.king.wxpay.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * XML工具类
 * @author taomk
 * @version 1.0
 * @since 15-7-10 下午4:08
 */
public class SimpleXml {

	public static byte[] marshall(Object bean){
        try {  
            JAXBContext context = JAXBContext.newInstance(bean.getClass());
            Marshaller marshaller = context.createMarshaller();
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            marshaller.marshal(bean, out);
            return out.toByteArray();
        } catch (Exception e) {  
            e.printStackTrace();
        }
        return null;
	}

    public static Document domParse(byte[] bytes){
        try{
            ByteArrayInputStream is=new ByteArrayInputStream(bytes);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = factory.newDocumentBuilder();
            Document doc = dBuilder.parse(is);
            return doc;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T unmarshall(Class<T> clazz,InputStream is){
        try{
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            T obj=(T)unmarshaller.unmarshal(is);
            return obj;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T unmarshall(Class<T> clazz,Node node){
        try{
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            T obj=(T)unmarshaller.unmarshal(node);
            return obj;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T unmarshall(Class<T> clazz,byte[] bytes){
        try{
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            ByteArrayInputStream in=new ByteArrayInputStream(bytes);
            T obj=(T)unmarshaller.unmarshal(in);
            return obj;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
